import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
// import { DataTableModule, SharedModule } from 'primeng/primeng';
import { Farm } from '../../../entity/farm.model';
import { ApplicationService } from '../../../service/application.service';
import { DynamicReportService } from '../../../service/dynamic-report.service';
@Component({
  selector: 'app-corporate-indicator',
  templateUrl: './corporate-indicator.component.html',
  styleUrls: ['./corporate-indicator.component.css']
})
export class CorporateIndicatorComponent implements OnInit {
  farms: Farm[] = [];

  //当前风场集合
  currentFarms: Farm[] = [];
  //当前风场Id集合
  currentFarmIds: number[] = [];
  //指标集合
  targets: any[] = [
    { name: '发电量(万kWh)', key: 'ActivePower', value: 1, isChecked: true },
    { name: '平均风速(m/s)', key: 'WindSpeed', value: 2, isChecked: true },
    /*  { name: '上网电量(万kWh)', key: 'powergrid', value: 3, isChecked: true },
     { name: '网购电量(万kWh)', key: 'powerwg', value: 4, isChecked: true } */
  ];
  //结束时间
  endtime = new Date();
  //开始时间
  starttime: Date = new Date(this.endtime.getFullYear(), this.endtime.getMonth(), this.endtime.getDate() - 1);
  //点击的指标集合
  points: string[] = ['ActivePower', 'WindSpeed'/* , 'powergrid', 'powerwg' */];
  //公司级指标集合
  corporateIndicators: any[] = [];
  selectedCorporateIndicators: any[] = [];
  //错误信息
  message: string;
  //是否显示弹出层
  isShow: boolean = false;
  /**
   *是否可以跨年查询
   *
   * @type {boolean}
   * @memberof CorporateIndicatorComponent
   */
  isAcrossYear: boolean = false;
  /**
   *日期格式化
   *
   * @type {*}
   * @memberof CorporateIndicatorComponent
   */
  en: any;
  constructor(
    private http: Http,
    public application: ApplicationService,
    private dynamicReportService: DynamicReportService,
  ) { }

  ngOnInit() {
    this.en = {
      firstDayOfWeek: 0,
      dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
      dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
      dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
      monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
      monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
      today: '今天',
      clear: '清除'
    };
    if (this.application.currentMenuParams && this.application.currentMenuParams['isAcrossYear']) {
      this.isAcrossYear = this.application.currentMenuParams['isAcrossYear'].paramValue == 'true' ? true : false;
    } else {
      this.isAcrossYear = false;
    }
    if (!this.isAcrossYear) {
      if (this.starttime.getFullYear() !== this.endtime.getFullYear()) {
        this.starttime = new Date(this.endtime.getFullYear(), 0, 1);
      }
    }
    this.farms = this.application.currentUserFarms.filter(farm => farm.farmCategory === 'winfarm');;//当前用户的有权限的的风场
    this.farms.forEach(o => {
      o.isChecked = true;
      this.currentFarms.push(o);
    });
    this.onSearch();
  }

  // 点击风场事件
  public onClickFarm(farm: Farm) {
    farm.isChecked = !farm.isChecked;
    if (farm.isChecked) {
      farm.isChecked = true;
      this.currentFarms.push(farm);
    } else {
      farm.isChecked = false;
      this.currentFarms.splice(this.currentFarms.findIndex(o => o.farmId == farm.farmId), 1);
    }

  }
  //指标点击事件
  public onClickTarget(e: any, target: any) {
    target.isChecked = !target.isChecked;
    if (target.isChecked) {
      this.points.push(target.key);
    } else {
      this.points.splice(this.points.findIndex(item => item === target.key), 1);
    }
    this.points.sort();
  }
  //关闭弹出层事件
  close() {
    this.isShow = false;
  }
  //查询事件
  onSearch() {
    if (!this.isAcrossYear) {
      if (this.endtime.getFullYear() !== this.starttime.getFullYear()) {
        this.message = `不能跨年查询`;
        this.isShow = true;
        return false;
      }
    }
    if (this.endtime > new Date()) {
      this.message = `结束时间不能大于当前时间！`;
      this.isShow = true;
    } else if (this.starttime > this.endtime) {
      this.message = `起始时间不能大于结束时间！`;
      this.isShow = true;
    } else if (this.points.length <= 0) {
      this.message = `指标不能为空！`;
      this.isShow = true;
    } else if (this.currentFarms.length <= 0) {
      this.message = `风场不能为空！`;
      this.isShow = true;
    } else {
      this.currentFarmIds = [];
      this.currentFarms.forEach(farm => {
        this.currentFarmIds.push(farm.farmId);
      })
      this.dynamicReportService.getDynamicReportByfarmIDs(this.currentFarmIds, this.points, this.starttime, this.endtime)
        .then(res => {

          if (!res || !res.length) { return false; };
          this.corporateIndicators = [...res];
          // 创建一个公司对象并添加到数组首位
          const corporate = { name: '|公司', pointValueList: [], type: 0 };
          this.corporateIndicators[0].pointValueList.forEach(point => {
            corporate.pointValueList.push({ key: point.key, value: 0 });
          });
          this.corporateIndicators.unshift(corporate);

          // 整合成想要的数据
          this.corporateIndicators.forEach(item => {
            item.pointValueList.forEach(pointValue => {
              // tslint:disable-next-line:forin
              for (const key in pointValue) {
                item[pointValue.key] = pointValue.value;
              };
            });
            // 层级结构
            if (item.type == 1) {
              item.name = '|—' + item.name;
            } else if (item.type == 2) {
              item.name = '|——' + item.name;
            }
          })
          //风场指标点相加
          const array1 = this.corporateIndicators.filter(o => o.type == 1); // 过滤出来的风场
          this.points.forEach(point => {
            array1.forEach(obj => {
              for (let key in obj) {
                if (point == key) {
                  corporate[point] += Number(obj[key]);
                }
              }
            });
          });
          // this.corporateIndicators[0].WindSpeed = Number(Number(this.corporateIndicators[0].WindSpeed) / Number(array1.length)).toFixed(2);

          let allWind = 0; // 风场的平均风速 * 风场的风机个数
          let turbTotal = 0; // 所有风场的风机总和
          array1.forEach(ary => {
            allWind += Number(ary.WindSpeed) * Number(ary.turbNumber);
            turbTotal += Number(ary.turbNumber);
          });
          this.corporateIndicators[0].WindSpeed = turbTotal == 0 ? 0 : Number(allWind / turbTotal).toFixed(2);//公司的平均风速

          this.corporateIndicators.forEach(obj => {
            delete obj.pointValueList;
            for (let o in obj) {
              if (this.points.find(point => o == point && o != 'WindSpeed')) {
                obj[o] = (obj[o] / 10000).toFixed(4);
              }
            }
          });

        })
        .catch(error => console.log(error));
    }
  }

}



// WEBPACK FOOTER //
// ./src/app/module/dynamic-report/corporate-indicator/corporate-indicator.component.ts
